/**
 * Created by Administrator on 2015/4/19.
 *
 * @see https://github.com/donpark/hbs
 * @see https://github.com/dpolivy/hbs-utils
 */
var express = require('express');
var compression = require('compression');
var http = require('http');
var session = require('cookie-session');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var app = express();
var server = http.createServer(app);
var port = process.env.PORT || 3000;
var path = require('path');
var hbs = require('hbs');
var hbsutils = require('hbs-utils')(hbs);
var dao = require('./model/dao');

//打开数据库连接
dao.openDB();

//监听端口
server.listen(port, function () {
    console.log('Server listening at port %d', port);
});

//使用 middleware(中间件)
/**
 * @see https://github.com/senchalabs/connect#middleware
 * @see https://www.npmjs.com/package/compression
 */
app.use(compression());//compress all requests
/**
 * 关于express的session
 * @link http://www.cnblogs.com/qiuyeyaozhuai/archive/2013/04/28/3043157.html
 */
//由于cookie需要加密session_id的值，所以一定要传入一个密钥字符串（任意）来加密
app.use(cookieParser('encrypt'));
app.use(session({
    key: 'express:session',//name/key  都表示cookie里面sessionId的键
    keys: ['nSessionId']
}));//session

app.use(bodyParser.urlencoded({
    extended: true
}));
app.use(bodyParser.json());


//定义静态文件路径
app.use(express.static(path.join(__dirname, '/public')));
/**
 * 关于express http get/post 各种参数的获取
 * @link http://blog.csdn.net/dan_blog/article/details/7463291
 */
//使用路由
require('./router')(app, express);


app.set('view engine', 'hbs');  // 用hbs作为模版引擎
//app.set('view engine', 'html');
app.engine('hbs', hbs.__express);
console.log('path:  ', path.join(__dirname, './views'));
app.set('views', path.join(__dirname, './views')); // 模版所在路径


//注册全局变量
hbs.localsAsTemplateData(app);//把app的render方法进行包装

//注册handlebars 的Partial (子模板?)根据文件名 {{>  filename}}
//hbs.registerPartials(path.join(__dirname, '/views'));
hbsutils.registerWatchedPartials(path.join(__dirname, 'views'));

require('./config').registerHelper(hbs);
//导出app
require('./config').initglobalApp(app);

//初始化信息
require('./init');
